using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace BlancoWorld.EventReceiversManager 
{
    public class EventReceiversManagerPage : LayoutsPageBase
    {
        protected SPWeb _spWeb;
        protected SPList _spList;
        protected Guid _spListId;

        protected SPGridView gridEventHandlers;
        protected ToolBarButton tbAddEventReceiver;
        protected EventReceiverCollectionBinder ercb = null;

        public string AddEventHandlerUrl
        {
            get
            {
                return String.Format("{0}/_layouts/BlancoWorld.EventReceiversManager/AddEventReceiver.aspx?ListId={1}&SourceUrl={0}{2}",
                    _spWeb.Url, Server.UrlEncode(_spListId.ToString()), Request.Url.PathAndQuery);    
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            SiteMapProvider smp = SiteMap.Providers["SPXmlContentMapProvider"];

            SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve += new SiteMapResolveEventHandler(provider_SiteMapResolve);

            try
            {
                _spWeb = SPControl.GetContextWeb(Context);
                _spListId = new Guid(Request.QueryString["List"].ToString());
                _spList = _spWeb.Lists[_spListId];
            }
            catch (Exception)
            {
                throw new Exception("Invalid list ID.");
            }

            tbAddEventReceiver.NavigateUrl = AddEventHandlerUrl;
            
            gridEventHandlers.AllowGrouping = true;
            gridEventHandlers.AllowGroupCollapse = true;
            gridEventHandlers.GroupField = "EventReceiverType";
            gridEventHandlers.GroupFieldDisplayName = "Event Receiver Type";
        }


        protected override void OnLoad(EventArgs e)
        {
            ercb = new EventReceiverCollectionBinder(this, _spListId);
            foreach (SPEventReceiverDefinition evDef in _spList.EventReceivers)
            {
                ercb.AddEventReceiver(evDef.Id, evDef.Type.ToString(), evDef.Assembly, evDef.Class, evDef.SequenceNumber);
            }

            string sourceUrl = _spWeb.Url + Request.Url.PathAndQuery;
            ercb.BindGrid(gridEventHandlers, sourceUrl);
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);

            //detach from the static SiteMapResolve event and restore localization mode              
            SiteMap.Providers["SPXmlContentMapProvider"].EnableLocalization = true;
            SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve -= new SiteMapResolveEventHandler(provider_SiteMapResolve);
        }

        protected virtual bool IsSamePage(HttpContext context1, HttpContext context2)
        {
            //by default, the contexts are considered the same if they            
            //map to the same file and the same listid/itemid       
            return ((Server.MapPath(context1.Request.AppRelativeCurrentExecutionFilePath) ==
                Server.MapPath(context2.Request.AppRelativeCurrentExecutionFilePath)) &&
                (context1.Request.QueryString == context2.Request.QueryString));
        }

        /// <summary>       
        /// Overrides the breadcrumbs with a new one in the format       
        /// [site]>[repository list]>[page title].       
        /// </summary>       
        protected SiteMapNode provider_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
        {
            if (!IsSamePage(Context, e.Context))
            {
                e.Provider.EnableLocalization = true;
                return e.Provider.CurrentNode;
            }

            SiteMapNode pageTitleNode;
            SiteMapNode settingsNode;
            try
            {
                // Trun off localization, so that the custom nodes do not get overwritten                 
                e.Provider.EnableLocalization = false;

                // Clone some node to get a valid node object and modify it.                 
                settingsNode = e.Provider.RootNode.ChildNodes[0].Clone();
                settingsNode.Url = String.Format("{0}/_layouts/listedit.aspx?List={1}",
                    _spWeb.Url, Server.UrlEncode(_spList.ID.ToString()));
                settingsNode.Title = "Settings";
                settingsNode.ChildNodes = new SiteMapNodeCollection();

                // Add as many new nodes as you need here                 
                pageTitleNode = new SiteMapNode(e.Provider, Guid.NewGuid().ToString());
                pageTitleNode.Title = "Event Receivers";
                settingsNode.ChildNodes.Add(pageTitleNode);
                pageTitleNode.ParentNode = settingsNode;
            }
            catch (Exception)
            {
                return e.Provider.CurrentNode;
            }
            return pageTitleNode;
        }
    }
}
